"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserModel = void 0;
const RedisConfig_1 = require("../config/RedisConfig");
const RetCodeDefine_1 = require("../config/RetCodeDefine");
const Logger_1 = require("../engine/utils/Logger");
const RedisManager_1 = require("../engine/utils/RedisManager");
const UserSysInfo_1 = require("./UserSysInfo");
const DateUtil_1 = require("../engine/utils/DateUtil");
const ProtoUtils_1 = require("../engine/socketserver/protocol/ProtoUtils");
const ProtoConfig_1 = require("../engine/socketserver/protocol/ProtoConfig");
const ZoneModel_1 = require("./ZoneModel");
const Config_1 = require("../config/Config");
class UserModel {
    constructor() {
        this.serverIdList = [];
    }
    //初始user唯一Id
    static initOnlyId() {
        return __awaiter(this, void 0, void 0, function* () {
            let redis = RedisManager_1.RedisManager.instance.getRedis(RedisConfig_1.RedisConfig.Database_Index.Users);
            this.onlyId = (yield redis.hlenPromise(this.Redis_Key.users)) + 1;
            Logger_1.Logger.log("initOnlyId==", this.onlyId);
        });
    }
    //redis数据转换为对象
    static redis2User(obj, sysInfoPack) {
        let user = new UserModel();
        user.userId = obj["userId"];
        user.userName = obj["userName"];
        user.pass = obj["pass"];
        user.createTime = obj["createTime"];
        user.lastLoginIp = obj["lastLoginIp"];
        user.lastLoginTime = obj["lastLoginTime"];
        user.sysInfo = UserSysInfo_1.UserSysInfo.proto2SysInfo(sysInfoPack);
        user.token = obj["token"];
        user.serverIdList = obj["serverIdList"];
        return user;
    }
    //根据用户名从redis拿到用户信息
    static getUserFromRedis(userName) {
        return __awaiter(this, void 0, void 0, function* () {
            let redis = RedisManager_1.RedisManager.instance.getRedis(RedisConfig_1.RedisConfig.Database_Index.Users);
            let obj = yield redis.hgetPromise(this.Redis_Key.users, userName);
            return obj;
        });
    }
    //注册
    static register(userName, pass) {
        return __awaiter(this, void 0, void 0, function* () {
            let ret = RetCodeDefine_1.RetCodeDefine.LoginError_NoUser;
            let obj = yield this.getUserFromRedis(userName);
            if (!obj) {
                let user = new UserModel();
                user.userId = this.onlyId;
                this.onlyId++;
                user.userName = userName;
                user.pass = pass;
                user.createTime = DateUtil_1.default.now();
                user.toUsersRedis();
                ret = RetCodeDefine_1.RetCodeDefine.OK;
            }
            else {
                ret = RetCodeDefine_1.RetCodeDefine.RegisterError_HadUser;
            }
            return ret;
        });
    }
    //登录
    static login(userName, pass, sysInfoPack, loginType) {
        return __awaiter(this, void 0, void 0, function* () {
            let ret = RetCodeDefine_1.RetCodeDefine.LoginError_NoUser;
            let data = yield this.getUserFromRedis(userName);
            let user;
            if (!data) {
                ret = RetCodeDefine_1.RetCodeDefine.LoginError_NoUser;
            }
            else {
                let obj = JSON.parse(data);
                if (loginType == 1) { //密码登录
                    if (obj["pass"] == pass) {
                        ret = RetCodeDefine_1.RetCodeDefine.OK;
                        user = this.redis2User(obj, sysInfoPack);
                    }
                    else {
                        Logger_1.Logger.log("登录密码错误", obj["pass"], pass, obj["pass"] == pass);
                        ret = RetCodeDefine_1.RetCodeDefine.LoginError_NoPass;
                    }
                }
                else if (loginType == 2) { //token登录
                    if (obj["token"] == pass) {
                        ret = RetCodeDefine_1.RetCodeDefine.OK;
                        user = this.redis2User(obj, sysInfoPack);
                    }
                    else {
                        Logger_1.Logger.log("登录token错误", obj["token"], pass, obj["token"] == pass);
                        ret = RetCodeDefine_1.RetCodeDefine.LoginError_NoPass;
                    }
                }
            }
            let resultObj = {
                "ret": ret,
                "user": user
            };
            Logger_1.Logger.log("login====", data, resultObj);
            return resultObj;
        });
    }
    toProto() {
        let respPack = ProtoUtils_1.ProtoUtils.Create(ProtoConfig_1.ProtoConfig.struct_user_info);
        respPack.setUserid(this.userId);
        respPack.setUsername(this.userName);
        respPack.setCreatetime(this.createTime);
        respPack.setLastlogintime(this.lastLoginTime);
        respPack.setLastloginip(this.lastLoginIp);
        respPack.setToken(this.token);
        return respPack;
    }
    //存储用户信息到users;
    toUsersRedis() {
        let redis = RedisManager_1.RedisManager.instance.getRedis(RedisConfig_1.RedisConfig.Database_Index.Users);
        if (Config_1.Config.serverType == Config_1.Config.ServerType_List.GameServer) {
            if (!this.serverIdList) {
                this.serverIdList = [];
            }
            this.serverIdList.push(ZoneModel_1.ZoneModel.nowZone.server_id);
        }
        redis.hsetPromise(UserModel.Redis_Key.users, this.userName, JSON.stringify(this));
    }
    // public toUserServerListRedis() {
    //     let redis: RedisClient = RedisManager.instance.getRedis(RedisConfig.Database_Index.Users);
    //     let key: string = this.userName + "_" + ZoneModel.nowZone.server_id
    //     redis.hsetPromise(UserModel.Redis_Key.user_servers, key, JSON.stringify(this));
    // }
    static test() {
        let user = new UserModel();
        user.userId = 1;
        user.userName = "abcd";
        user.pass = "666666";
        user.sysInfo = new UserSysInfo_1.UserSysInfo();
        Logger_1.Logger.log("test=-=====", JSON.stringify(user));
        let redis = RedisManager_1.RedisManager.instance.getRedis(RedisConfig_1.RedisConfig.Database_Index.Users);
        redis.hsetPromise(this.Redis_Key.users, user.userName, JSON.stringify(user));
    }
}
exports.UserModel = UserModel;
UserModel.Redis_Key = {
    users: "users",
    user_servers: "user_servers",
};
UserModel.onlyId = 1;
